<?php

class wwy_dispatcher
{
    protected $_route_list = array();

    public static $client = '';
    public static $route = '';

    public function __construct()
    {
        $this->_set_route_list();
    }

    protected function _set_route_list()
    {
        require_once PROJECT_ROOT_PATH . '/no_public/dispatcher/route_list/route_list.php';
        
        $this->_route_list = wwy_get_route_list();
        //var_dump($this->_route_list); exit();
    }

    public function dispatch()
    {
        $route = $this->_set_route();

        if(empty($this->_route_list[$route])){
           echo '页面不存在'; exit();
        }

        $route_info = $this->_route_list[$route];
        if($route_info['type'] == 'default'){
            require_once $route_info['action_path'];

            $action = new $route_info['action_class_name'];
            $action->run();
        }

    }

    protected function _set_route()
    {
        $route_tmp = !(empty($_GET['route'])) ? trim($_GET['route']) : 'index';

        $regex = '/^(pc|mobile)_/i';
        $count = preg_match($regex, $route_tmp, $values);

        if($count){
            $client = $values[1];
            $route = $route_tmp;
        }else{
            $client = $this->_get_client();
            $route = $client . '_' . $route_tmp;
        }

        self::$client = $client;
        self::$route = $route;

        return self::$route;
    }

    /**
     * 检查并获取【客户端】平台
     */
    protected function _get_client()
    {
        if($this->_is_mobile()){
            $client = 'mobile';
        }else{
            $client = 'pc';
        }
        //$client = 'mobile';

        return $client;
    }

    protected function _is_mobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }

        // 如果via信息含有wap则一定是移动设备
        if ( isset ($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap") )
        {
            return true;
        }

        //判断手机发送的客户端标志
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $user_agent = strtolower($user_agent);
        $client_keywords = array('wap', 'mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if( preg_match("/(" . implode('|', $client_keywords) . ")/i", $user_agent) )
        {
            return true;
        }

        return false;
    }
}


